<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/jq-1.12.4.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        a {
            text-decoration: none;
            color: #4E6EF2;
            display: block;
            width: 36px;
            height: 36px;
            line-height: 36px;
            border-radius: 5px;
            margin: 5px;
            float: left;
            background-color: #ddd;
            text-align: center;
            font-size: 14px;
        }

        .active {
            background-color: #4E6EF2;
            color: #ffffff;
        }

        .prev-page,
        .next-page {
            width: 80px;
        }

        a:hover {
            background-color: #4E6EF2;
            color: #ffffff;
        }
    </style>
</head>

<body>
    <div id="page">
        <div class="page-inner">
            <a href="#" class="prev-page">&lt;上一页</a>
            <a href="#" class="next-page">下一页&gt;</a>
        </div>
    </div>
</body>
<script>
    let currentPage = 1
    let total = 20

    function appendList(pageNum) {
        //1、先删除所有的page-item
        let pageItem = $('.page-item')
        if (pageItem) {
            pageItem.remove()
        }
        //2、判断prev-page
        let prevPage = $('.prev-page')
        pageNum > 1 ? prevPage.show() : prevPage.hide()
        //3、确定当前页码的范围
        let start = pageNum <= 6 ? 1 : pageNum - 5
        let end = start + 9
        //如果超过总条数时，等于总条数
        if (end >= total) {
            end = total
        }
        //使用循环拼接元素
        for (let i = start; i <= end; i++) {
            let a = $(`<a class="page-item">${i}</a>`)
            //给点击的元素添加
            if (pageNum == i) {
                a = $(`<a class="page-item active">${i}</a>`)
            }
            a.insertBefore($('.next-page'))
            //给a元素绑定事件
            a.click(function () {
                let index = parseInt(a.html())
                appendList(index)
                currentPage = index
            })
        }
    }

    $(function () {
        //页面首次加载第一页
        appendList(1)
        //点击下一页的操作
        $('.next-page').click(function () {
            currentPage++
            if (currentPage >= total) {
                currentPage = total
            }
            appendList(currentPage)
        })
        //点击上一页的操作
        $('.prev-page').click(function () {
            currentPage--
            if (currentPage <= 0) {
                currentPage = 1
            }
            appendList(currentPage)
        })
    })
</script>

</html>